#include "long_cmd.h"

int gets_client(int netfd, const train_t *train)
{
    // char filename[4096]={0};
    // memcpy(filename,train.buff,train.length);
    int fd = open(train->buff, O_RDWR | O_CREAT | O_TRUNC, 0666);
    ERROR_CHECK(fd, -1, "open file");

    while (1)
    {
        train_t train_file;
        int filedata_length_ret = recv(netfd, &train_file.length,
                                       sizeof(train_file.length), MSG_WAITALL);
        ERROR_CHECK(filedata_length_ret, -1, "recv filedata train.length");

        if (train->length != 1000)
        {
            printf("train.length=%d\n", train_file.length);
        }
        if (train_file.length == 0)
        {
            break;
        }
        int filedata_cmdType_ret =
            recv(netfd, &train_file._cmdType, sizeof(train_file._cmdType),
                 MSG_WAITALL);
        ERROR_CHECK(filedata_cmdType_ret, -1, "recv filedata_buff_ret");
        int filedata_buff_ret =
            recv(netfd, &train_file.buff, train_file.length, MSG_WAITALL);
        ERROR_CHECK(filedata_buff_ret, -1, "recv filedata_buff_ret");

        int write_ret = write(fd, train_file.buff, train_file.length);
        ERROR_CHECK(write_ret, -1, "write");
    }
    return 0;
}

int puts_client(int netfd, const char *filename)
{
    int access_ret = access(filename, F_OK);
    if (access_ret == -1)
    {
        return access_ret;
    }
    train_t train;
    train.length = strlen(filename);
    memcpy(train.buff, filename, train.length);
    int send_filename_ret =
        send(netfd, &train,
             sizeof(train.length) + sizeof(train._cmdType) + train.length,
             MSG_NOSIGNAL);
    ERROR_CHECK(send_filename_ret, -1, "send fliename");

    int fd = open(filename, O_RDWR);
    ERROR_CHECK(fd, -1, "open file");

    while (1)
    {
        ssize_t read_ret = read(fd, train.buff, sizeof(train.buff));
        ERROR_CHECK(read_ret, -1, "read train.buff");

        train.length = read_ret;
        if (read_ret != 1000 && read_ret != -1)
        {
            printf("read_ret=%lu\n", read_ret);
        }

        int send_filedata_ret =
            send(netfd, &train,
                 sizeof(train.length) + sizeof(train._cmdType) + train.length,
                 MSG_NOSIGNAL);
        ERROR_CHECK(send_filedata_ret, -1, "send filedata");

        if (read_ret == 0)
        {
            break;
        }
    }
    return 0;
}
